package com.learn.configuration;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.org.apache.xpath.internal.operations.String;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfiguration {
    // 读源码发现，若自定义redisTemplate则spring boot内封装好的redisTemplate则会失效（@ConditionalOnMissingBean）
    @Bean
    public RedisTemplate<String, Object> serializerRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        // 为了开发方便直接使用<String, Object>类型
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        
        // 配置具体的序列化方式
        //  JSON序列化
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        
        //  String序列化
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        
        //  key采用String的方式序列化
        template.setKeySerializer(stringRedisSerializer);
        //  hash_key采用String的方式序列化
        template.setHashKeySerializer(stringRedisSerializer);
        //  value采用JSON的方式序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //  hash_value采用JSON的方式序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        
        template.afterPropertiesSet();
        return template;
    }
}
